
/**
 * 设置缓存
 * @param {*} key 键
 * @param {*} value 值
 * @param {*} exp 过期时间 小于 365、366 则，按天算。否则按时间戳算
 */
export function setLocalStorageItem (key, value, expires) {
  let obj = {}
  obj.value = value
  obj.time = new Date().getTime()

  // expires 类型
  if (expires === null) {
    delete obj.expires
  } else if (typeof expires === 'object') {
    obj.expires = expires.getTime() - obj.time
  } else if (typeof expires === 'number') {
    if ((expires | 0) !== expires) {
      throw new Error('expires must be integer number!')
    }
    // expires 小于 365、366 则，按天算。否则按时间戳算
    if (expires <= getYearDays() && expires > 0) {
      obj.expires = expires * 1000 * 60 * 60 * 24
    } else if (expires > getYearDays()) {
      obj.expires = expires
    } else if (expires <= 0) {
      removeLocalStorageItem(key)
    }
  }
  localStorage.setItem(key, JSON.stringify(obj))
}

/**
 * 读取缓存
 * @param {*} key 键
 */
export function getLocalStorageItem (key) {
  var obj = JSON.parse(localStorage.getItem(key))
  if (obj === 'null' || obj === null) return null
  let expires = obj.expires
  let now = new Date().getTime()
  let time = obj.time

  if (now - time >= expires || now < time) {
    localStorage.removeItem(key)
    return null
  } else {
    return obj.value
  }
}

// removeLocalStorageItem
export function removeLocalStorageItem (key) {
  if (getLocalStorageItem(key) !== null) {
    localStorage.removeItem(key)
    return getLocalStorageItem(key) === null
  }
  return true
}

// 获取一年的天数
function getYearDays () {
  return new Date().getFullYear() % 4 === 0 ? 366 : 365
}
